package com.jiang.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class PeerWriter extends Thread{
    private static final Logger LOGGER = LoggerFactory.getLogger(PeerWriter.class);
    private Socket socket;
    private ArrayList<String> outputBuffer;
    private boolean runFlag = true;


    public PeerWriter(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            outputBuffer = new ArrayList<String>();
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);//允许自动刷新
            while (runFlag){
                //这个循环显然会不断地进行
                if(!outputBuffer.isEmpty() && outputBuffer.get(0) != null){
                    //若输出缓冲区不为空且首个不为空
                    for(String line:outputBuffer){
                        LOGGER.info("Sending "+line+" to "+socket.getInetAddress());
                        //将输出数据缓冲区的数据输出到该客户端套接字
                        out.println(line);//打印一个对象，然后终止该行。
                    }
                    outputBuffer = new ArrayList<String>();//全输出之后，重新申请内存
                    outputBuffer.add(null);

                }
                outputBuffer = new ArrayList<String>();//全输出之后，重新申请内存
                outputBuffer.add(null);
                TimeUnit.MILLISECONDS.sleep(200);
            }
        } catch (Exception e) {
            LOGGER.error("Peer "+socket.getInetAddress()+" disconnected.", e);
        }
    }

    /**
     * 写入缓冲
     * @param data
     */

    public void write(String data){
        if(!outputBuffer.isEmpty()){
            if(outputBuffer.get(0) == null){
                outputBuffer.remove(0);
            }
        }
        outputBuffer.add(data);
    }

    public void shutdown(){
        runFlag = false;
    }
}
